package com.xqq.juc;

import java.util.concurrent.Semaphore;

public class SemaphoreDebugger {
    private static final Semaphore semaphore = new Semaphore(3); // 允许3个线程同时访问

    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            new Thread(new Worker(i), "Worker-" + i).start();
        }
    }

    static class Worker implements Runnable {
        private final int id;

        public Worker(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            try {
                System.out.printf("[%tT] Worker-%d 尝试获取许可...\n", System.currentTimeMillis(), id);

                // 获取许可（可设置超时）
                semaphore.acquire();

                System.out.printf("[%tT] Worker-%d 获得许可，开始工作\n", System.currentTimeMillis(), id);

                // 模拟工作
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                System.out.printf("[%tT] Worker-%d 释放许可\n", System.currentTimeMillis(), id);
                semaphore.release();
            }
        }
    }
}